package com.ruoyi.system.service.impl;

import java.beans.Transient;
import java.util.*;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.ISubCommunityService;
import org.springframework.transaction.annotation.Transactional;

/**
 * sub_communityService业务层处理
 * 
 * @author wfj
 * @date 2025-10-29
 */
@Service
public class SubCommunityServiceImpl implements ISubCommunityService 
{
    @Autowired
    private SubCommunityMapper subCommunityMapper;
    @Autowired
    private StreetCommunityMapper streetCommunityMapper;
    @Autowired
    private CommunityMapper communityMapper;
    @Autowired
    private DistrictCountyMapper districtCountyMapper;
    @Autowired
    private ResidentialBuildingsMapper residentialBuildingsMapper;

    /**
     * 查询sub_community
     * 
     * @param id sub_community主键
     * @return sub_community
     */
    @Override
    public SubCommunity selectSubCommunityById(String id)
    {
        return subCommunityMapper.selectSubCommunityById(id);
    }

    /**
     * 查询sub_community列表
     * 
     * @param subCommunity sub_community
     * @return sub_community
     */
    @Override
    public List<SubCommunity> selectSubCommunityList(SubCommunity subCommunity)
    {
        return subCommunityMapper.selectSubCommunityList(subCommunity);
    }

    /**
     * 新增sub_community
     * 
     * @param subCommunity sub_community
     * @return 结果
     */
    @Override
    public int insertSubCommunity(SubCommunity subCommunity)
    {
        subCommunity.setCreateTime(DateUtils.getNowDate());
        return subCommunityMapper.insertSubCommunity(subCommunity);
    }

    /**
     * 修改sub_community
     * 
     * @param subCommunity sub_community
     * @return 结果
     */
    @Override
    public int updateSubCommunity(SubCommunity subCommunity)
    {
        subCommunity.setUpdateTime(DateUtils.getNowDate());

        int value= subCommunityMapper.updateSubCommunity(subCommunity);
        return value;
    }

    /**
     * 批量删除sub_community
     * 
     * @param ids 需要删除的sub_community主键
     * @return 结果
     */
    @Override
    public int deleteSubCommunityByIds(String[] ids)
    {
        return subCommunityMapper.deleteSubCommunityByIds(ids);
    }

    /**
     * 删除sub_community信息
     * 
     * @param id sub_community主键
     * @return 结果
     */
    @Override
    public int deleteSubCommunityById(String id)
    {
        return subCommunityMapper.deleteSubCommunityById(id);
    }

    @Override
    public List<Map<String, String>> customSql(String sqlStr)
    {
        //先保存表单数据

        String sql="select * from \"22\"";

        return subCommunityMapper.customSql(sqlStr);
    };

    /**
     * 保存填报数据
     * @param subCommunity
     * @return
     */
    @Transactional
    public String saveData(SubCommunity subCommunity) {
        if(StrUtil.isBlank(subCommunity.getId())) {
            // 生成新ID
            String newId = UUID.randomUUID().toString();
            subCommunity.setId(newId);
            subCommunity.setCreateTime(new Date());

            this.doInsert(subCommunity); // 执行插入操作

            // 根据不同类型插入数据
            if(subCommunity.getAdministrativeRegionLevel().equals("form_type_residential")) {
                subCommunityMapper.insertSubCommunity(subCommunity);
            } else if(subCommunity.getAdministrativeRegionLevel().equals("form_type_street")) {
                StreetCommunity streetCommunity = new StreetCommunity();
                BeanUtils.copyProperties(subCommunity, streetCommunity);
                streetCommunityMapper.insertStreetCommunity(streetCommunity);
            } else if(subCommunity.getAdministrativeRegionLevel().equals("form_type_community")) {
                Community community = new Community();
                BeanUtils.copyProperties(subCommunity, community);
                communityMapper.insertCommunity(community);
            } else if(subCommunity.getAdministrativeRegionLevel().equals("form_type_district")) {
                DistrictCounty districtCounty = new DistrictCounty();
                BeanUtils.copyProperties(subCommunity, districtCounty);
                districtCountyMapper.insertDistrictCounty(districtCounty);
            } else if(subCommunity.getAdministrativeRegionLevel().equals("form_type_building")) {
                ResidentialBuildings residentialBuildings = new ResidentialBuildings();
                BeanUtils.copyProperties(subCommunity, residentialBuildings);
                residentialBuildingsMapper.insertResidentialBuildings(residentialBuildings);
            }

            return newId; // 返回新生成的ID
        } else {
            this.doUpdata(subCommunity); // 执行更新操作

            // 更新逻辑
            if(subCommunity.getAdministrativeRegionLevel().equals("form_type_residential")) {
                subCommunityMapper.updateSubCommunity(subCommunity);
            } else if(subCommunity.getAdministrativeRegionLevel().equals("form_type_street")) {
                StreetCommunity streetCommunity = new StreetCommunity();
                BeanUtils.copyProperties(subCommunity, streetCommunity);
                streetCommunityMapper.updateStreetCommunity(streetCommunity);
            } else if(subCommunity.getAdministrativeRegionLevel().equals("form_type_community")) {
                Community community = new Community();
                BeanUtils.copyProperties(subCommunity, community);
                communityMapper.updateCommunity(community);
            } else if(subCommunity.getAdministrativeRegionLevel().equals("form_type_district")) {
                DistrictCounty districtCounty = new DistrictCounty();
                BeanUtils.copyProperties(subCommunity, districtCounty);
                districtCountyMapper.updateDistrictCounty(districtCounty);
            } else if(subCommunity.getAdministrativeRegionLevel().equals("form_type_building")) {
                ResidentialBuildings residentialBuildings = new ResidentialBuildings();
                BeanUtils.copyProperties(subCommunity, residentialBuildings);
                residentialBuildingsMapper.updateResidentialBuildings(residentialBuildings);
            }

            return subCommunity.getId(); // 返回现有ID
        }
    }
    /**
     * 执行表单数据更新操作
     * @param subCommunity
     */
    public void  doInsert(SubCommunity subCommunity)
    {
        //先保存表单数据
        //判断表单数据是否为空-基本数据
        if(StrUtil.isNotBlank(subCommunity.getFormData()) && StrUtil.isNotBlank(subCommunity.getFormConfig()))
        {
            //添加
            //formDataId
            //String id = UUID.randomUUID().toString();
            long id=UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
            StringBuilder stringBuilder= new StringBuilder();
            StringBuilder val= new StringBuilder();
            JSONObject jsonObject= JSONUtil.parseObj(subCommunity.getFormData());
            //循环数据创建SQL
            stringBuilder.append("insert into \""+subCommunity.getFormDataName()+"\"");
            //key
            stringBuilder.append("(");
            // value
            val.append("VALUES ( ");
            int number=1;
            for(String key : jsonObject.keySet()){
                Object value = jsonObject.get(key);
                // 处理每个键值对
                stringBuilder.append("\""+key+"\",");
                val.append("\'"+value+"\',");
                number++;
            }
            //最后补充一个id
            stringBuilder.append("id");
            val.append("\'"+id+"\'");
            stringBuilder.append(")");
            val.append(" )");
            stringBuilder.append(val);
            subCommunityMapper.customSql(stringBuilder.toString());
            //保存社区数据
            subCommunity.setCreateTime(new Date());
            subCommunity.setFormDataId(String.valueOf(id));
            subCommunity.setId(UUID.randomUUID().toString());

        }
        //判断表单数据是否为空-基本数据
        if(StrUtil.isNotBlank(subCommunity.getFormDataKpi()) && StrUtil.isNotBlank(subCommunity.getFormConfigKpi()))
        {
            //添加
            //formDataId
            //String id = UUID.randomUUID().toString();
            long id=UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
            StringBuilder stringBuilder= new StringBuilder();
            StringBuilder val= new StringBuilder();
            JSONObject jsonObject= JSONUtil.parseObj(subCommunity.getFormDataKpi());
            //循环数据创建SQL
            stringBuilder.append("insert into \""+subCommunity.getFormDataNameKpi()+"\"");
            //key
            stringBuilder.append("(");
            // value
            val.append("VALUES ( ");
            int number=1;
            for(String key : jsonObject.keySet()){
                Object value = jsonObject.get(key);
                // 处理每个键值对
                stringBuilder.append("\""+key+"\",");
                val.append("\'"+value+"\',");
                number++;
            }
            //最后补充一个id
            stringBuilder.append("id");
            val.append("\'"+id+"\'");
            stringBuilder.append(")");
            val.append(" )");
            stringBuilder.append(val);
            subCommunityMapper.customSql(stringBuilder.toString());

            subCommunity.setFormDataKpiId(String.valueOf(id));

        }
    }

    /**
     * 执行表单数据更新操作
     * @param subCommunity
     */
    public void doUpdata(SubCommunity subCommunity) {
        //判断表单数据是否为空-基本数据
        if (StrUtil.isNotBlank(subCommunity.getFormData()) && StrUtil.isNotBlank(subCommunity.getFormConfig())) {
            //更新
            String sql = " update 表 set key =value where id =";
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder where = new StringBuilder();
            JSONObject jsonObject = JSONUtil.parseObj(subCommunity.getFormData());
            //循环数据创建SQL
            stringBuilder.append("update \"" + subCommunity.getFormDataName() + "\"" + " set");
            int number = 1;
            for (String key : jsonObject.keySet()) {
                if (key == "id") {
                    //where
                    where.append(" where \"" + key + "\" = '" + jsonObject.get(key) + "',");
                } else {
                    if (number == jsonObject.keySet().size()) {
                        stringBuilder.append(" \"" + key + "\" ='" + jsonObject.get(key) + "'");
                    } else {
                        stringBuilder.append(" \"" + key + "\" ='" + jsonObject.get(key) + "',");
                    }
                }
                number++;
            }
            subCommunityMapper.customSql(stringBuilder.toString());
        }
        if (StrUtil.isNotBlank(subCommunity.getFormDataKpi()) && StrUtil.isNotBlank(subCommunity.getFormConfigKpi()))
        {
            //更新
            String sql = " update 表 set key =value where id =";
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder where = new StringBuilder();
            JSONObject jsonObject = JSONUtil.parseObj(subCommunity.getFormDataKpi());
            //循环数据创建SQL
            stringBuilder.append("update \"" + subCommunity.getFormDataNameKpi() + "\"" + " set");
            int number = 1;
            for (String key : jsonObject.keySet()) {
                if (key == "id") {
                    //where
                    where.append(" where \"" + key + "\" = '" + jsonObject.get(key) + "',");
                } else {
                    if (number == jsonObject.keySet().size()) {
                        stringBuilder.append(" \"" + key + "\" ='" + jsonObject.get(key) + "'");
                    } else {
                        stringBuilder.append(" \"" + key + "\" ='" + jsonObject.get(key) + "',");
                    }
                }
                number++;
            }
            subCommunityMapper.customSql(stringBuilder.toString());
        }
    }

    @Override
    public List<Map<String, Object>>  selectSubCommunityListForApp(SysUser user) {
        return subCommunityMapper.selectSubCommunityListForApp(user);
    }
}
